package com.education.ai.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import lombok.extern.slf4j.Slf4j;
import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * 千问API配置
 */
@Slf4j
@Configuration
public class QwenApiConfig {
    
    @Value("${qwen.api.key}")
    private String apiKey;
    
    @Value("${qwen.api.uri}")
    private String apiUri;
    
    @Value("${qwen.api.model}")
    private String model;
    
    @Value("${qwen.api.endpoint:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation}")
    private String apiEndpoint;
    
    @Bean
    public WebClient qwenWebClient() {
        log.info("初始化千问API WebClient, 端点: {}", apiEndpoint);
        
        // 检查API密钥是否有效
        if (apiKey == null || apiKey.isEmpty() || apiKey.startsWith("sk-12dff")) {
            log.error("千问API密钥未正确设置，请检查application.yml中的qwen.api.key配置或环境变量");
            log.error("当前配置的API密钥: {}", apiKey);
        } else {
            log.info("千问API密钥已配置: {}", apiKey.substring(0, 6) + "****");
        }
        
        // 创建连接提供者，设置最大连接数和获取超时
        ConnectionProvider provider = ConnectionProvider.builder("qwen-api-pool")
            .maxConnections(50)
            .maxIdleTime(Duration.ofSeconds(30))
            .maxLifeTime(Duration.ofMinutes(5))
            .pendingAcquireTimeout(Duration.ofSeconds(60))
            .build();
        
        // 创建HTTP客户端，设置连接超时、读写超时
        HttpClient httpClient = HttpClient.create(provider)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000) // 连接超时30秒
            .responseTimeout(Duration.ofSeconds(120)) // 响应超时2分钟
            .doOnConnected(conn -> 
                conn.addHandlerLast(new ReadTimeoutHandler(120, TimeUnit.SECONDS)) // 读超时2分钟
                    .addHandlerLast(new WriteTimeoutHandler(30, TimeUnit.SECONDS)) // 写超时30秒
            );
        
        // 添加日志以确认WebClient正在使用正确的URL和密钥
        log.info("创建WebClient，基础URL: {}", apiEndpoint);
        
        return WebClient.builder()
                .baseUrl(apiEndpoint)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024)) // 16MB
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }
    
    // 添加一个方法来检查API连接
    @Bean
    public void checkApiConnection() {
        log.info("正在检查千问API连接...");
        try {
            // 简单的测试请求
            WebClient testClient = WebClient.builder()
                .baseUrl("https://dashscope.aliyuncs.com/api/v1")
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .build();
            
            String result = testClient.get()
                .uri("/services")
                .retrieve()
                .bodyToMono(String.class)
                .block(Duration.ofSeconds(10));
            
            log.info("千问API连接测试成功: {}", result != null ? "已收到响应" : "无响应");
        } catch (Exception e) {
            log.error("千问API连接测试失败: {}", e.getMessage());
        }
    }
    
    public String getApiKey() {
        return apiKey;
    }
    
    public String getApiUri() {
        return apiUri;
    }
    
    public String getModel() {
        return model;
    }
} 